package Model;

import java.sql.ResultSet;

import static Model.DataBase.insertEscape;
import static Model.DataBase.searchEscape;

/**
 * Created by msi on 2017/6/4.
 * Deal with the operation of table account
 */
public class AccountDB {
    private static DataBase dataBase = new DataBase();

    public static void create(Account account){
        String sql_create_account = "call create_account('"
                + insertEscape(account.getUsername())+"','"+
                insertEscape(account.getPassword())+"','"+
                insertEscape(account.getToken())+"'"+")";
        dataBase.executeStatement(sql_create_account);
    }

    public static String getUsername(int id){
        ResultSet rs = dataBase.retrieveData("select username from account where id=" + id);
        try {
            if(rs.next()){
                return rs.getString(1);
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static boolean usernameUnique(String username){
        ResultSet rs = dataBase.retrieveData("select * from account where username='" + searchEscape(username) + "'");
        try {
            if(rs.next()){
                return false;
            }
            else{
                return true;
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    public static int identify(String username, String password){
        ResultSet rs = dataBase.retrieveData("select id, password from account where username='" + username + "'");
        try {
            if(rs.next()){
                if(password.equals(rs.getString(2))){
                    return Integer.parseInt(rs.getString(1));
                }
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    public static int identify(String token){
        ResultSet rs = dataBase.retrieveData("select id from account where token='" + token + "'");
        try {
            if(rs.next()){
                return Integer.parseInt(rs.getString(1));
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    public static void updateToken(int id, String token){
        String sql_update_token = "update account set token='" + token +"' where id=" + id;
        dataBase.executeStatement(sql_update_token);
    }
}
